package yxy.game.pm2.command.friend;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.FriendMessage;
import yxy.game.pm2.message.PlayerMessage;
import yxy.game.pm2.module.friend.FriendModule;
import yxy.game.pm2.module.friend.NeedFriendList;
import yxy.game.pm2.module.player.PlayerHandle;

import java.util.ArrayList;
import java.util.Collection;

/** 好友 刷新推荐 */
@MessageType(proto = Command.FriendUpdate, classtype = FriendMessage.FriendUpdateRequest.class)
public class CMD_FriendUpdate extends Command<FriendMessage.FriendUpdateRequest> {

	@Override
	public void execute(MessageSource messageSource, FriendMessage.FriendUpdateRequest request) {
		String playerCode = messageSource.getTag();

		FriendMessage.FriendUpdateResponse.Builder response = FriendMessage.FriendUpdateResponse.newBuilder();

		PlayerBean playerBean = PlayerBean.get(playerCode);
		ServerBean serverBean = ServerBean.get(playerBean.getServerId());
		AreaBean areaBean = AreaBean.get(serverBean.getAreaId());

		// 刷新推荐玩家
		Collection<String> recommend = new NeedFriendList(areaBean.getGroupId()).recommend();
		FriendModule playerModule = FriendModule.get(playerCode);
		try {
			if (playerModule.tryLock()) {
				ArrayList<PlayerBean> list = new ArrayList<>();
				for (String code : recommend) {
					if (playerModule.getFriend().contains(code) || playerModule.getBlack().contains(code) || code.equals(playerCode)) {
						continue;
					}
					FriendModule targetModule = FriendModule.get(code);
					if (targetModule.getApply().contains(playerCode) || targetModule.getBlack().contains(playerCode)) {
						continue;
					}
					PlayerBean bean = PlayerBean.get(code);
					if (bean == null) {
						continue;
					}
					list.add(bean);
					if (list.size() >= 10) {
						break;
					}
				}
				PlayerHandle playerHandle = new PlayerHandle();
				for (PlayerBean bean : list) {
					PlayerMessage.PlayerSimpleInfo.Builder builder = playerHandle.playerSimpleInfo(bean);
					builder.setOnline(bean.online());

					response.addRecommend(builder);
				}

				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			playerModule.unlock();
		}
	}

	private void send(MessageSource messageSource, FriendMessage.FriendUpdateResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}